package struts.utils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import struts.bean.XmlBean;

public class StrutsConfigUtil {

	public static String getUrl(String url){
		return url.split("\\.")[0];
	}
	
	
	public static Map<String,XmlBean> loadStrutsConfig(String filePath) throws JDOMException, IOException{
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(filePath));
		Element root = document.getRootElement();
		Element action = root.getChild("action-mapping");
		List<Element> actions = action.getChildren();
		Map<String,XmlBean> xmlBeanMap=new HashMap<String,XmlBean>();
		for(Element a:actions){
			XmlBean xb=new XmlBean();
			Element beans=root.getChild("beans");
			List<Element> beanList=beans.getChildren();
			for(Element	b:beanList){
				//System.out.println(b.getAttribute("name")+","+a.getAttribute("name"));
				if(b.getAttributeValue("name").equals(a.getAttributeValue("name"))){
					xb.setFormClass(b.getAttributeValue("class"));
					//System.out.println(b.getAttributeValue("class"));
					break;
				} 
			}
			xb.setBeanName(a.getAttributeValue("name"));
			xb.setActionType(a.getAttributeValue("type"));
			String path = a.getAttributeValue("path");
			xb.setPath(path);
			List<Element> forward = a.getChildren();
			Map<String,String> map=new HashMap<String,String>();
			for(Element f:forward){
				map.put(f.getAttributeValue("name"), f.getAttributeValue("value"));
				map.put(f.getAttributeValue("name"), f.getAttributeValue("value"));
			}
			xb.setActionForward(map);
			xmlBeanMap.put(path, xb);
		}
		return xmlBeanMap;
	}
	
	public static void main(String[] args) throws JDOMException, IOException {
		Map<String,XmlBean> xmlbs=loadStrutsConfig("resources/struts-config.xml");
		Set<String> set=xmlbs.keySet();
		Iterator<String> i=set.iterator();
		while(i.hasNext()){
			String key=i.next();
			XmlBean xb=xmlbs.get(key);
			System.out.println(xb.toString());
		}
		
	}
}
